package com.itheima.ai.repository;

import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class InMemoryChatHistoryRepository implements ChatHistoryRepository{
    private final Map<String,List<String>> chatHistory = new HashMap<>(); // 存储聊天记录的Map，键为业务类型，值为会话ID列表（内存存储）

    @Override
    public void save(String type, String chatId) {
        /*if(!chatHistory.containsKey(type)){
            chatHistory.put(type, new ArrayList<>());
        }
        List<String> chatIds = chatHistory.get(type);*/
        List<String> chatIds = chatHistory.computeIfAbsent(type, k -> new ArrayList<>());//和上面的注释代码等价
        if(chatIds.contains(chatId)){
            return;
        }
        chatIds.add(chatId);
    }

    @Override
    public List<String> getChatIds(String type) {
        /*List<String> chatIds = chatHistory.get(type);
        return chatIds != null ? chatIds : new ArrayList<>();*/
        return chatHistory.getOrDefault(type, /*new ArrayList<>() 此为空集合（List.of()也一样）*/List.of());  //和上面的注释代码等价
    }
}
